package com.cqupt.scanning.handler.exception;


import com.cqupt.scanning.system.utils.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody //为了返回数据
    public R error(Exception e) {
        if (e.getMessage() != null) {
            if (e.getMessage().contains("不允许访问")) {
                return R.error().code(30005).message("无权限访问");
            }
        }
        e.printStackTrace();
        return R.error().message("服务错误,请联系管理员");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R methodArgumentNotValidException(MethodArgumentNotValidException e) {
        return R.error().code(40001).message(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public R httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return R.error().code(40002).message(e.getMessage());
    }

    //自定义异常
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public R selfError(MyException e) {
        e.printStackTrace();
        return R.error().code(e.getCode()).message(e.getMsg());
    }

}
